#!/usr/bin/env python

# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Street Identity Demo Attribute Provider - API for retrieving street address."""

from google.appengine.dist import use_library
use_library('django', '1.2')
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import logging
import cgi

from lib import utils
from lib import authn
from lib.loggable import loggable
from lib.error import handle_error

import model

__author__ = "Maciej Machulak"
__maintainer__ = "Maciej Machulak"
__email__ = "mmachulak@google.com"

__copyright__ = "Copyright 2011, Google Inc."
__license__ = "Apache License 2.0"
__version__ = "0.1"
__status__ = "Prototype"

class RequestAddressHandler(webapp.RequestHandler):
    
    @authn.login_required
    @loggable('request address')     
    def get(self): 
        
        client_id = self.request.get('client_id')
        logging.debug('client id: %s' % client_id)
        if client_id is None or client_id == '':
          logging.error('client id not present - application not recognized')
          handle_error(self)
          return 
        
        client = model.Application.all().filter('client_id = ', client_id).get()
        if client is None:
          logging.error('client with the provided id does not exist')
          handle_error(self)
          return
        logging.debug('client retrieved from db')
        
        redirect_uri = self.request.get('redirect_uri') 
        logging.debug('user will be redirected to %s' % redirect_uri)
        
        user = self.user
        
        logging.debug('checking if there is already a verified address for the user')
        address_list = model.Address.all().filter('verified = ', 'true').get()
        if address_list:
          logging.debug('there is already a verified street address for the user - returning client')
          self.redirect(redirect_uri + '?request=fail&error=address_exists')
          return

        values = {
         'user': user,
         'client': client,
         'redirect_uri': redirect_uri
        }
        path = os.path.join(os.path.dirname(__file__), '../templates/add_address.html')
        self.response.out.write(template.render(path, values))
     
    @authn.login_required   
    @loggable('add address')      
    def post(self):
        
        client_id = self.request.get('client_id')
        logging.debug('client id: %s' % client_id)
        if client_id is None or client_id == '':
          logging.error('client id not present - application could not be recognized')
          handle_error(self)
          return 
        client = model.Application.all().filter('client_id = ', client_id).get()
        if client is None:
          logging.error('no client associated with the provided client id')
          handle_error(self)
          return        

        logging.debug('client retrieved from db')
                
        redirect_uri = self.request.get('redirect_uri')
        logging.debug('user will be redirected to %s' % redirect_uri)
                
        user = self.user

        address = cgi.escape(self.request.get('address'))
        address_type = cgi.escape(self.request.get('address_type'))
        address_desc = cgi.escape(self.request.get('desc'))
        
        new_address = model.Address(
                              address = address,
                              type = address_type,
                              code = utils.random(),
                              desc = address_desc,
                              user = user)
        new_address.put()        
        logging.debug('stored new address for the user')
       
        values = {
         'user': user,
         'address': new_address,
         'client': client,
         'redirect_uri': redirect_uri
        }
        
        path = os.path.join(os.path.dirname(__file__), '../templates/confirm_add_address.html')
        self.response.out.write(template.render(path, values))        